package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
)

func EchoHandler(writer http.ResponseWriter, req *http.Request) {

	for name, values := range req.Header {

		writer.Header()[name] = values
	}
	writer.Header().Set("Host", req.Host)

	if os.Getenv("VERSION") != "" {

		writer.Header().Set("VERSION", os.Getenv("VERSION"))
	}
}

func HealthHandler(resp http.ResponseWriter, req *http.Request) {

	resp.Write([]byte("ok"))
}

type StatusRecorder struct {
	http.ResponseWriter
	Status int
}

func (r *StatusRecorder) WriteHeader(status int) {
	r.Status = status
	r.ResponseWriter.WriteHeader(status)
}

func logging(h http.Handler) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		recorder := &StatusRecorder{
			ResponseWriter: w,
			Status:         200,
		}
		h.ServeHTTP(recorder, r)
		log.Printf(" %s - %s, status: %d", r.RemoteAddr, r.URL.Path, recorder.Status)
	}
}

func main() {

	fmt.Println("启动 Http Server... ")
	http.HandleFunc("/echo", logging(http.HandlerFunc(EchoHandler)))
	http.HandleFunc("/healthz", logging(http.HandlerFunc(HealthHandler)))
	err := http.ListenAndServe(":8000", nil)
	if err != nil {
		log.Fatalf("服务启动失败，%v", err)
	}
}
